<?php
/**
 * 区块链账号
 */
namespace app\admin\controller;
use app\admin\model\AccountAddress as AccountAddressModel;
use app\common\server\Rsa as RsaModel;
use app\common\server\Sha256 as Sha256Model;
use app\api\model\BaseConfig as BaseConfigModel;
use app\common\Trc20;

class AccountAddress extends Admin
{
    private $postField = 'real_address,secret_key,type';

    /**
     * 列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DbException
     */
    function index(){
        if(empty($this->request->post())){
            return view('index');
        }else{
            $limit  = $this->request->post('limit', 20, 'intval');
            $page = $this->request->post('page', 1, 'intval');
            $order  = $this->request->post('order', '', 'serach_in');	//排序字段
            $sort  = $this->request->post('sort', '', 'serach_in');		//排序方式
            $where = [];

            $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';
            //获取账号列表
            $res = AccountAddressModel::getList($page,$limit,formatWhere($where),$orderby);

            foreach ($res['data'] as &$v){
                $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            }

            $data['status'] = 200;
            $data['data'] = $res;
            return json($data);
        }
    }

    /**
     * 添加账号
     * @return \think\response\Json
     */
    function add(){
        $data = $this->request->only(explode(',',$this->postField),'post',null);
        $sha256 = new Sha256Model();

        //获取钱包前缀
        $address_prefix = BaseConfigModel::config_data('address_prefix');
        //获取钱包总长度
        $wallet_address_length = BaseConfigModel::config_data('wallet_address_length');
        $random_num = bcsub($wallet_address_length,mb_strlen($address_prefix,'utf-8'));
        if($random_num <= 0) $random_num = 18;

        $da = [
            'address'   =>  $address_prefix.$sha256->random($random_num),    //随机生成账号
            'real_address'   =>  $data['real_address'],
            'secret_key'   =>  $data['secret_key'],
            'type'   =>  $data['type'],
            'add_time'  =>  time()
        ];

        $res = AccountAddressModel::insertGetId($da);

        if(empty($res)) return json(['status'=>200,'data'=>$res,'msg'=>'添加失败']);
        return json(['status'=>200,'data'=>$res,'msg'=>'添加成功']);
    }

    /**
     * 添加账号
     * @return \think\response\Json
     */
    function addDapp(){
        $data = $this->request->post('data', '', 'serach_in');
        $sha256 = new Sha256Model();

        //获取钱包前缀
        $address_prefix = BaseConfigModel::config_data('address_prefix');
        //获取钱包总长度
        $wallet_address_length = BaseConfigModel::config_data('wallet_address_length');
        if($wallet_address_length > 0){ //有设定账号长度
            //账号长度减去前缀长度 = 剩余长度
            $random_num = bcsub($wallet_address_length,mb_strlen($address_prefix,'utf-8'));
        }else{
            //无设定账号长度 跟钱包长度一致
            $random_num = bcsub(mb_strlen($data[0]['real_address'],'utf-8'),mb_strlen($address_prefix,'utf-8'));
        }
        if($random_num <= 0) $random_num = 18; //剩余长度小于0 默认改为18位

        //添加50个DAPP账号
        foreach ($data as $v){
            if(!empty($v['secret_key'])){
                $da = [
                    'address'   =>  $address_prefix.$sha256->random($random_num),    //随机生成账号
                    'real_address'   =>  $v['real_address'],
                    'secret_key'   =>  $v['secret_key'],
                    'type'   =>  2,
                    'add_time'  =>  time()
                ];
                AccountAddressModel::insertGetId($da);
            }
        }
        return json(['status'=>200,'msg'=>'添加成功']);
    }

    /**
     * 添加TRC20 100个账号
     * @return \think\response\Json
     */
    function addTrc20(){
        for ($i = 0;$i < 50;$i++){
            Trc20::generate_address();
        }
        return json(['status'=>200,'msg'=>'添加成功']);
    }

    /**
     * 账号详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getEdit(){
        $id =  $this->request->post('id', '', 'serach_in');
        if(!$id) throw new ValidateException ('参数错误');
        $res = AccountAddressModel::getDetails($id);
//        $Rsa = new RsaModel('path');
//        $res['secret_key'] = $Rsa->privDecrypt($res['secret_key']);
//        $res['secret_key'] = substr($res['secret_key'],0,60);
        $res['key'] = $res['secret_key'];
        return json(['status'=>200,'data'=>$res]);
    }

    /**
     * 修改账号
     * @return \think\response\Json
     */
    function update(){
        $field = 'id,address,'.$this->postField;
        $data = $this->request->only(explode(',',$field),'post',null);
        $da['status'] = 1;

        $res = AccountAddressModel::where('id',$data['id'])->update($data);

        if(empty($res)) return json(['status'=>200,'data'=>$res,'msg'=>'修改失败']);
        return json(['status'=>200,'data'=>$res,'msg'=>'修改成功']);
    }

    /**
     * 删除账号
     * @return \think\response\Json
     */
    function delete(){
        $idx =  $this->request->post('id', '', 'serach_in');
        if(!$idx) throw new ValidateException ('参数错误');
        AccountAddressModel::destroy(['id'=>explode(',',$idx)],true);
        return json(['status'=>200,'msg'=>'操作成功']);
    }


    function remaining_available(){
        $data['trc20_num'] = AccountAddressModel::where('status',1)->where('type',1)->count();
        $data['dapp_num'] = AccountAddressModel::where('status',1)->where('type',2)->count();
        return json(['status'=>200,'data'=>$data]);
    }

}